package com.wiloon.java.network.network.nettyhttpserver.monitor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Roy on 2015/10/31;
 */
public class RequestMonitor implements Runnable {
    private final static Logger logger = LoggerFactory.getLogger(RequestMonitor.class);

    private static boolean stopMonitor = false;

    private static int lastRequestTotal;
    private static long lastRequestTime;

    private static int lastResponseTotal;
    private static long lastResponseTime;

    public RequestMonitor() {
    }

    public void run() {
        logger.info("monitor thread started");
        AvgValue requestAverage = new AvgValue();
        AvgValue responseAverage = new AvgValue();
        while (!stopMonitor) {
            try {
                long requestDuration = RequestCounter.getTime() - lastRequestTime;
                long responseDuration = ResponseCounter.responseTime - lastResponseTime;

                int requestCount = RequestCounter.getCount() - lastRequestTotal;
                int responseCount = ResponseCounter.responseTotal.get() - lastResponseTotal;
                logger.trace("period={}", requestDuration);

                double requestPerSecond = Math.floor(requestCount / (requestDuration / 1000.0));
                double responsePerSecond = Math.floor(responseCount / (responseDuration / 1000.0));

                logger.info("request[current={},avg={},total={}];response[current={},avg={},total={}];",
                        requestPerSecond, Math.floor(requestAverage.calculate(requestPerSecond)), RequestCounter.getCount(), responsePerSecond, responseAverage.calculate(responsePerSecond), ResponseCounter.get());

                lastResponseTotal = ResponseCounter.responseTotal.get();
                lastResponseTime = ResponseCounter.responseTime;
                lastRequestTotal = RequestCounter.getCount();
                lastRequestTime = RequestCounter.getTime();
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
